package com.gavin.algorithm.hash;

import java.util.HashMap;

/**
 * TinyURL is a URL shortening service where you enter a URL such as
 * https://leetcode.com/problems/design-tinyurl and it returns a short URL such
 * as http://tinyurl.com/4e9iAk.
 * 
 * Design the encode and decode methods for the TinyURL service. There is no
 * restriction on how your encode/decode algorithm should work. You just need to
 * ensure that a URL can be encoded to a tiny URL and the tiny URL can be
 * decoded to the original URL.
 * 
 * @author lenovo
 *
 */
public class TinyURL {
	private HashMap<String, String> index = new HashMap<String, String>();
	private HashMap<String, String> revIndex = new HashMap<String, String>();
	private final static String BASE_HOST = "http://tinyurl.com/";

	public String encode(String longUrl) {
		if (revIndex.containsKey(longUrl))
			return BASE_HOST + revIndex.get(longUrl);
		String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String key = null;

		do {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < 6; i++) {
				int point = (int) (Math.random() * charSet.length());
				sb.append(charSet.charAt(point));
			}
			key = sb.toString();
		} while (index.containsKey(key));

		index.put(key, longUrl);
		revIndex.put(longUrl, key);

		return BASE_HOST + key;
	}

	public String decode(String shortUrl) {
		return index.get(shortUrl.replace(BASE_HOST, ""));
	}

	public static void main(String[] args) {
		TinyURL tiny = new TinyURL();
		String str = "https://leetcode.com/problems/design-tinyurl";
		String shor1 = tiny.encode(str);
		System.out.println(shor1);
		String long1 = tiny.decode("http://tinyurl.com/ihtRia");
		System.out.println(long1);
	}

}
